<?php
/**
 * IG_Web_Element_Table
 *
 * @author maomao.thx@gmail.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: Table.php 586 2011-05-31 10:07:18Z mmxie $
 */
require_once 'IG/Web/Element.php';
class IG_Web_Element_Table extends IG_Web_Element
{
    protected $_rows = array();

    /**
     * @return array
     */
    public function getRows()
    {
        return $this->_rows;
    }

    /**
     *
     * @param array $rows
     * @return IG_Web_Element_Table
     */
    public function setRows($rows)
    {
        $this->_rows = $rows;
        return $this;
    }

    /**
     *
     * @param row
     * @return IG_Web_Element_Table
     */
    public function addRow($row)
    {
        $this->_rows[] = $row;
        return $this;
    }

    /**
     *
     * @param string $content
     * @return string
     */
    public function render($content)
    {
        $attribs       = $this->getAttribs();

        if ($this->getName() != null) {
            $attribs['name'] = $this->getName();
        }

        if ($this->getId() != null) {
            $attribs['id'] = $this->getId();
        }

        if (isset($attribs['enable']) && $attribs['enable'] == false) {
            return $content;
        }

        // build the element
        $xhtml = '<table'
                . $this->_htmlAttribs($attribs)
                . '>' . PHP_EOL;
        if (empty($this->_rows)) {
            return $xhtml . '</table>';
        }
        $xhtmlHeaderRow = '';
        $xhtmlRow = '';
        $xhtmlFooterRow = '';
        foreach ($this->_rows as $row) {
            if ($row instanceof IG_Web_Element_Table_HeaderRow) {
                $xhtmlHeaderRow .= $row->render('') . PHP_EOL;
            } else if ($row instanceof IG_Web_Element_Table_FooterRow) {
                $xhtmlFooterRow .= $row->render('') . PHP_EOL;
            } else {
                $xhtmlRow .= $row->render('') . PHP_EOL;
            }
        }
        if ($xhtmlHeaderRow != '' || $xhtmlFooterRow != '') {
            $xhtml .= ' <thead>' . PHP_EOL
                . $xhtmlHeaderRow
                . ' </thead>' . PHP_EOL;
            $xhtml .= '  <tbody>' . PHP_EOL
                . $xhtmlRow
                . '  </tbody>' . PHP_EOL;
            $xhtml .= '  <tfoot>' . PHP_EOL
                . $xhtmlFooterRow
                . '  </tfoot>' . PHP_EOL;
        } else {
            $xhtml .= $xhtmlHeaderRow . $xhtmlRow . $xhtmlFooterRow;
        }

        return $content . $xhtml . '</table>';
    }
}